<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item v-if="isAuth('mvs:payment:delete')">
        <el-input v-model="dataForm.key" placeholder="用户" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          style="width: 400px"
          v-model="dataForm.dateRange"
          clearable
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
<!--        <el-button v-if="isAuth('mvs:payment:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>-->
        <el-button v-if="isAuth('mvs:payment:delete')" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.detailList" border>
            <el-table-column prop="ticketId" label="罚单编号" header-align="center" align="center" />
            <el-table-column
              prop="paymentMoney"
              :formatter="(row) => row.paymentMoney.toLocaleString('en-US', {  minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' 元'"
              header-align="center"
              label="缴费金额"
              align="right" />
            <el-table-column prop="username" label="缴费人" header-align="center" align="center" />
            <el-table-column prop="createTime" label="缴费时间" header-align="center" align="center" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        v-if="isAuth('mvs:payment:delete')"
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="username"
        header-align="center"
        align="center"
        label="缴费人">
      </el-table-column>
      <el-table-column
        prop="paymentMoney"
        :formatter="(row) => row.paymentMoney.toLocaleString('en-US', {  minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' 元'"
        header-align="center"
        align="right"
        label="缴费金额">
      </el-table-column>
      <el-table-column
        prop="paymentTime"
        header-align="center"
        align="center"
        label="缴费时间">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
<!--          <el-button v-if="isAuth('mvs:payment:delete')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>-->
          <el-button type="text" size="small" @click="printReceipt(scope.row)">打印发票</el-button>
          <el-button v-if="isAuth('mvs:payment:delete')" type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './payment-add-or-update.vue'
  import { jsPDF } from 'jspdf'
  import { autoTable } from 'jspdf-autotable'
  import { font } from '../../../assets/font/song-normal'

  export default {
    data () {
      return {
        dataForm: {
          key: '',
          dateRange: []
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        dialogPrintVisible: false
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/mvs/payment/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key,
            'startDate': this.dataForm.dateRange ? this.dataForm.dateRange[0] : '',
            'endDate': this.dataForm.dateRange ? this.dataForm.dateRange[1] : ''
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定删除吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/mvs/payment/delete'),
            method: 'delete',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 创建发票的pdf
      createPdf (payment, logList) {
        const doc = new jsPDF()
        doc.addFileToVFS('song.ttf', font)
        doc.addFont('song.ttf', 'custom', 'normal')
        doc.setFont('custom')

        // 添加标题
        doc.setFontSize(16)
        doc.text('机动车缴费发票', 105, 10, { align: 'center' })

        // 表格
        autoTable(doc, {
          head: [['罚单编号', '缴费金额', '罚单状态']],
          body: logList.map(log => [ log.ticketId, log.paymentMoney, log.ticketStatus ]),
          startY: 30,
          theme: 'grid', // 使用网格主题
          styles: { font: 'custom', fontSize: 16 }
        })

        // 添加数据项
        doc.setFontSize(12)
        doc.text(`缴费人：张三`, 15, 80)
        doc.text(`缴费时间：${payment.paymentTime}`, 150, 80)
        doc.text(`发票编号：${payment.id}`, 15, 90)
        doc.text(`缴纳金额：￥${payment.paymentMoney}`, 150, 90)

        return doc
      },
      // 打印发票
      printReceipt (item) {
        // 获取缴纳记录对应的日志列表
        this.$http({
          url: this.$http.adornUrl(`/mvs/payment/list/log/${item.id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            const pdf = this.createPdf(item, data.logList)
            this.$confirm('已加载好发票数据，请您选择要执行的操作', '提示', {
              confirmButtonText: '下载',
              cancelButtonText: '预览',
              distinguishCancelAndClose: true
            }).then(() => pdf.save('机动车缴费发票.pdf'))
              .catch(action => {
                if (action === 'cancel') pdf.output('dataurlnewwindow')
              })
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    }
  }
</script>
